<template>
    <div class="container">
        <div class="content">
            <div class="left-wrap">
                <div class="btn-cont left">
                    <div>教室管理</div>
                    <el-button type="primary" @click="handleAdd()">新增教室</el-button>
                </div>
                <div class="table-cont">
                    <el-table ref="multipleTable" v-loading="classLoading" border highlight-current-row :data="classTable"
                        :element-loading-text="elementLoadingText" @selection-change="setSelectClassRows"
                        @row-click="onRowClick">
                        <el-table-column type="selection" align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip label="教室名称" prop="name" align="center">
                            <template #default="scope">
                                <div v-if="scope.row.editStatus">
                                    <el-input v-model="scope.row.newName" :placeholder="scope.row.name"
                                        class="input-cont"></el-input>
                                </div>
                                <div v-else>
                                    <div>{{ scope.row.name }}</div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column show-overflow-tooltip label="教室IP" prop="ip" align="center">

                            <template #default="scope">
                                <div v-if="scope.row.editStatus">
                                    <el-input v-model="scope.row.ip" :placeholder="scope.row.ip"
                                        class="input-cont"></el-input>
                                </div>
                                <div v-else>
                                    <div>{{ scope.row.ip }}</div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column show-overflow-tooltip label="楼栋" prop="building" align="center">

                            <template #default="scope">
                                <div v-if="scope.row.editStatus">
                                    <el-select v-model="scope.row.buildingId" placeholder="请选择楼栋"
                                        @change="changeBuilding(scope.row)">
                                        <el-option v-for="(item, inx) in buildOpt" :key="inx" :label="item.name"
                                            :value="item.id"></el-option>
                                    </el-select>
                                </div>
                                <div v-else>
                                    <div>{{ scope.row.building }}</div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column show-overflow-tooltip label="楼层" prop="floor" align="center">
                            <template #default="scope">
                                <div v-if="scope.row.editStatus">
                                    <el-select v-model="scope.row.floorId" placeholder="请选择楼层"
                                        @change="changeBuilding(scope.row)">
                                        <el-option v-for="(item, inx) in floorOpt" :key="inx" :label="item.name"
                                            :value="item.id"></el-option>
                                    </el-select>
                                </div>
                                <div v-else>
                                    <div>{{ scope.row.floor }}</div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="100">
                            <template #default="{ row }">
                                <el-button type="text" @click="handleEdit(row)">修改</el-button>
                                <!-- <el-button type="text" @click="handleConfirm(row)">
                                    确定
                                </el-button> -->
                            </template>
                        </el-table-column>
                    </el-table>

                    <vab-PagTable class="pagination-Box" :total="total" :page="queryForm.offset" :limit="queryForm.limit"
                        @changePage="changePage"></vab-PagTable>
                </div>
                <div class="btn-cont bottom-l">
                    <!-- <el-button type="primary" @click="handleCreate()">生成</el-button> -->
                    <el-button type="primary" @click="handleIssue()">下发</el-button>
                    <el-button type="primary" @click="handleDelLeft()">
                        删除
                    </el-button>
                    <el-button type="primary" :disabled="selectItems.length > 1" @click="handleCopy()">
                        复制
                    </el-button>
                    <el-input-number v-model="iptNum" @change="handleChange" />

                </div>
            </div>
            <div class="right-wrap">
                <div class="btn-cont right">
                    <el-button type="primary" :disabled="selectItems.length > 1" @click="handleNewLink()">
                        新增联动
                    </el-button>
                    <!-- <el-button @click="handleCreate()">生成</el-button> -->
                </div>
                <div class="table-cont">
                    <el-table ref="isLinkTable" v-loading="linkLoading" height="600" border highlight-current-row
                        :data="linkTable" :element-loading-text="elementLoadingText" @selection-change="setSelectLinkRows">
                        <el-table-column show-overflow-tooltip prop="deviceIp" label="联动IP" min-width="50" align="center">
                            <!-- <template slot-scope="{ row }">
                  <el-input v-model="row.delay" @change="IPInput(row)"></el-input>
              </template> -->
                        </el-table-column>
                        <el-table-column show-overflow-tooltip label="命令输入" min-width="100" align="center">

                            <template #default="scope">
                                <div class="row-wrap">
                                    <div>{{ scope.row.input }}</div>
                                    <el-button type="text" size="small" @click="rowCommand(scope.row, scope.row.input)">
                                        编辑
                                    </el-button>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column show-overflow-tooltip label="执行" min-width="260" align="center">
                            <template #default="scope">
                                <div class="row-wrap">
                                    <div class="row-cell">
                                        <span v-for="(item, i) in scope.row.exeConfig" :key="i">
                                            <span v-if="i" class="v_set">|</span>
                                            <span v-if="item.deviceId === -1">
                                                延时 - {{ item.deviceId }} - {{ item.action }}秒
                                            </span>
                                            <span v-else>
                                                {{ item.module }} - {{ item.deviceId }} -
                                                {{ item.communication }} -
                                                {{ item.action }}
                                            </span>
                                        </span>
                                    </div>
                                    <el-button type="text" size="small" @click="rowCarryOut(scope.row, 'exeConfig')">
                                        编辑
                                    </el-button>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column show-overflow-tooltip label="状态输出" min-width="260" align="center">
                            <template #default="scope">
                                <div class="row-wrap">
                                    <div class="row-cell">
                                        <span v-for="(item, i) in scope.row.output" :key="i">
                                            <span v-if="i" class="v_set">|</span>
                                            <span>
                                                {{ item.module }} - {{ item.deviceId }} -
                                                {{ item.communication }} - {{ item.action }} -
                                                {{ item.outputValue }}
                                            </span>
                                        </span>
                                    </div>
                                    <el-button type="text" size="small" @click="rowStatus(scope.row, 'output')">
                                        编辑
                                    </el-button>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column type="selection" align="center"></el-table-column>
                    </el-table>
                    <vab-PagTable class="pagination-Box" :total="total1" :page="queryForm1.page" :limit="queryForm1.limit"
                        @changePage="changePage1"></vab-PagTable>
                </div>
                <div class="btn-cont bottom-r">
                    <el-button type="primary" @click="handleDelRight()">删除</el-button>
                </div>
            </div>
        </div>

        <!--命令输入-->
        <el-dialog :title="'命令输入--' + this.rowNameId + '--' + this.rowName" :show-close="false" :model-value="dialogCommand"
            width="48%">
            <div class="dialog-cont">
                <div class="left-table">
                    <el-table height="580" v-loading="commandLoading" border ref="deviceTable" :data="deviceListTable"
                        highlight-current-row :element-loading-text="elementLoadingText" @row-click="onRowClickDevice">
                        <el-table-column fixed show-overflow-tooltip prop="id" label="设备ID"
                            align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip prop="title" label="设备名" align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip prop="brand" label="品牌" align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip prop="module" label="模块" align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip prop="ip" label="IP" align="center"></el-table-column>
                    </el-table>
                </div>
                <div class="list-cont">
                    <div class="title">{{ title }}</div>
                    <div class="list">
                        <el-radio-group v-model="curRadio" @change="curItemRadio">
                            <div v-for="(item, inx) in checkOpt" :key="inx" class="item">
                                <el-radio :label="item.communication + item.action">
                                    {{ item.communication }} - {{ item.name }}
                                </el-radio>
                            </div>
                        </el-radio-group>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelDialog">取 消</el-button>
                <el-button type="primary" @click="confirmDialog">确 定</el-button>
            </span>
        </el-dialog>

        <!--执行/状态输出-->
        <el-dialog :title="dialogTitle" :show-close="false" :model-value="dialogVisible" @close="dialogVisibleClose"
            width="80%">
            <div class="dialog-cont">
                <div class="left-table common-cont">
                    <el-table height="530" v-loading="commonLoading" border ref="commonDeviceTable" :data="commonTable"
                        :element-loading-text="elementLoadingText" highlight-current-row
                        @row-click="onRowClickCommonDevice">
                        <el-table-column fixed show-overflow-tooltip prop="id" label="设备ID"
                            align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip prop="title" label="设备名" align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip prop="brand" label="品牌" align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip prop="module" label="模块" align="center"></el-table-column>
                    </el-table>
                </div>
                <div class="list-cont list-center-cont">
                    <template v-if="flag">
                        <el-table height="470" v-loading="carryOutLoading" :data="carryOutTable"
                            :element-loading-text="elementLoadingText">
                            <el-table-column fixed show-overflow-tooltip label="行为">
                                <template #default="scope">
                                    <div class="row-wrap behavior-row">
                                        <el-checkbox v-model="scope.row.checked"
                                            @change="actionClick(scope.row)"></el-checkbox>
                                        <div>{{ scope.row.communication }} - {{ scope.row.name }}</div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column show-overflow-tooltip min-width="50px" prop="delay" label="延时">
                                <template #default="scope">
                                    <div class="row-wrap delay-row">
                                        <el-input v-model="scope.row.delay" @change="delayInput(scope.row)"></el-input>
                                        <div>秒</div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                    <template v-else>
                        <div class="title-status">{{ statusTitle }}</div>
                        <div class="list-status">
                            <div v-for="(item, inx) in statusCheckOpt" :key="inx" class="item-status">
                                <div class="title-cont">
                                    {{ item.communication }} - {{ item.name }}
                                </div>

                                <el-radio-group v-model="item.outputValue" @change="handleStatusRadio(item)">
                                    <div v-for="(el, _inx) in item.list" :key="_inx" class="ele-status">
                                        <el-radio :label="el.code">
                                            {{ el.label }}
                                        </el-radio>
                                    </div>
                                </el-radio-group>

                            </div>
                        </div>
                    </template>
                </div>
                <div class="right-table">
                    <el-table height="530" border ref="connectTable" v-loading="connectLoading" :data="connectTable"
                        highlight-current-row @row-click="onRowClickSort" :element-loading-text="elementLoadingText">


                        <el-table-column show-overflow-tooltip width="100" prop="order" label="执行顺序"
                            align="center"></el-table-column>
                        <!-- fixed -->

                        <el-table-column show-overflow-tooltip min-width="180px" label="执行内容" align="center">
                            <template #default="scope">
                                <template v-if="flag">
                                    <template v-if="scope.row.delay">
                                        延时 - -1 - {{ scope.row.delay }}秒 | {{ scope.row.module }} - {{ scope.row.id }} - {{
                                            scope.row.communication
                                        }} -
                                        {{ scope.row.action }}
                                    </template>
                                    <template v-else>
                                        {{ scope.row.module }} - {{ scope.row.id }} - {{ scope.row.communication }} -
                                        {{ scope.row.action }}
                                    </template>
                                </template>
                                <template v-else>
                                    {{ scope.row.module }} - {{ scope.row.id }} - {{ scope.row.communication }} -
                                    {{ scope.row.action }} -
                                    <span v-if="scope.row.outputValue == '1'">开</span>
                                    <span v-else>关</span>
                                </template>
                            </template>
                        </el-table-column>
                        <el-table-column show-overflow-tooltip min-width="30px" label="删除" align="center"
                            v-if="this.shanchuflog">
                            <template #default="scope">
                                <span @click="shanchu(scope.row)"
                                    style="display: inline-block; width: 100%;height: 100%;">x</span>
                            </template>

                        </el-table-column>

                    </el-table>
                    <div class="btn-move-cont">
                        <el-button type="text" icon="el-icon-arrow-up" @click="arrowUP">
                            上移
                        </el-button>
                        <el-button type="text" icon="el-icon-arrow-down" @click="arrowDown">
                            下移
                        </el-button>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="commonCancel">取 消</el-button>
                <el-button type="primary" @click="commonConfirm">确 定</el-button>
            </span>
        </el-dialog>
        <EditDialog ref="editDialogRef" @success="initClassRoom()"></EditDialog>
    </div>
</template>

<script>
import vabPagTable from './components/VabPagination/index.vue'
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import EditDialog from './EditDialog.vue';
export default {
    name: 'ClassroomManagement',
    components: {
        vabPagTable,
        EditDialog
    },
    props: {},
    data() {
        return {
            classLoading: false,
            queryForm: {
                query: '',
                sort: 'id',
                order: 'desc', // 排序方式：asc-升序;desc-降序
                offset: 1,
                limit: 10,
            },
            queryForm1: {
                query: '',
                sort: 'id',
                order: 'desc', // 排序方式：asc-升序;desc-降序
                offset: 1,
                page: 1,
                limit: 10,
            },
            total: 0,
            total1: 0,
            // roomId: null,
            multiple: [],
            classTable: [],
            selectItems: [],
            buildingId: '',
            buildOpt: [],
            floorOpt: [],
            elementLoadingText: '正在加载...',
            linkLoading: false,
            linkTable: [],
            selectLinkItems: [],
            dialogCommand: false,
            commandLoading: false,
            deviceListTable: [],
            title: '行为',
            rowName: '',
            rowNameId: '',
            curRadio: '',
            checkOpt: [],
            dialogTitle: '',
            dialogVisible: false,
            commonLoading: false,
            commonTable: [],
            flag: true,
            carryOutLoading: false,
            carryOutTable: [],
            statusTitle: '',
            statusCheckOpt: [],
            connectLoading: false,
            shanchuflog: true,
            connectTable: [],
            testarr: [],// 测试arr
            inputFrom: {
                id: null,
                roomId: null,
                roomCode: '',
                deviceId: null,
                deviceIp: '',
                communication: '',
                action: '',
            },
            carryOutFrom: {
                id: null,
                roomId: null,
                config: '',
            },
            resExeConfig: [],
            statusFrom: {
                id: null,
                roomId: null,
                config: '',
            },
            resOutput: [],
            isOpenRowStr: '',
            isOpenRowId: '',
            isCurrentLinkRowId: '', //选中的教室关联id
            curOutputRowId: '', //选中的输出内容id排序用
            curRow: {}, //选中的输出内容排序高亮用
            iptNum: 1
        }
    },
    watch: {
        buildingId: {
            handler(newV) {
                // console.log(newV);
                // this.initFloor(newV)
            },
            immediate: true,
            deep: true,
        },
        connectTable: {
            handler(newV) {
                if (!newV.length) return false
                newV.forEach((item, inx) => {
                    item.order = inx + 1
                })
            },
            immediate: true,
            deep: true,
        },
        multiple: {
            handler(newV) {
                if (!newV.length) return
                // this.roomId = newV[0].id
                this.statusFrom.roomId = newV[0].id
                this.carryOutFrom.roomId = newV[0].id
                this.inputFrom.roomId = newV[0].id
                this.inputFrom.roomCode = newV[0].roomCode
            },
            immediate: true,
            deep: true,
        },
    },
    created() {
        this.initBuildAll()
        this.initClassRoom()
    },
    mounted() { },
    methods: {
        setCurLinkRow() {
            // 让右侧教室关联的编辑项一直被选中
            if (this.isCurrentLinkRowId === '') return false
            if (!this.linkTable.length) return false
            this.linkTable.forEach((item) => {
                if (item.id === this.isCurrentLinkRowId) {
                    this.$refs.isLinkTable.setCurrentRow(item)
                }
            })
        },
        changeBuilding(val) {
            this.buildingId = val.buildingId
        },
        initFloor(_id) {
            EsAjax.post(ApiUrls.buildingfloor, { id: _id }).then(res => {
                if (res.data.code && res.data.code === 200) {
                    this.floorOpt = res.data.data
                }
            })

        },
        initBuildAll() {
            EsAjax.get(ApiUrls.buildAll).then(res => {
                if (res.data.code && res.data.code === 200) {
                    this.buildOpt = res.data.data
                }
            })

        },
        // 查询教室列表
        initClassRoom() {
            this.multiple = []
            let params = {}
            Object.keys(this.queryForm).forEach((key) => {
                params[key] = this.queryForm[key]
            })
            params.offset = params.offset - 1 // 后端从0开始，0：第一页...
            EsAjax.post(ApiUrls.roomDeviceList, params).then(res => {
                console.log(res, '22');
                if (res.data.code && res.data.code === 200) {
                    let arr = []
                    res.data.data.list.forEach((item) => {
                        arr.push({
                            editStatus: false,
                            ...item,
                        })
                    })
                    this.classTable = arr
                    this.total = res.data.data.totalCount

                    this.linkTable = []
                    this.$refs.multipleTable.setCurrentRow(this.classTable[0])
                    this.multiple.push(this.classTable[0])
                    this.initLink(this.classTable[0], 'init')
                }
            })

        },
        // 左右侧教室列表 分页
        // changeSize(data) {
        //   this.queryForm.limit = data
        //   this.initClassRoom()
        // },
        // changeSize1(data) {
        //   this.queryForm1.limit = data
        //   this.initLink(this.classTable[0], 'init')
        // },
        changePage(data) {
            this.queryForm.offset = data
            this.initClassRoom()
        },
        changePage1(data) {
            console.log(data);
            this.queryForm1.page = data
            this.initLink(this.classTable[0])
        },
        // 查询教室关联列表
        initLink(data, str) {
            this.linkLoading = true
            let params = {}
            Object.keys(this.queryForm1).forEach((key) => {
                params[key] = this.queryForm1[key]
            })
            if (str === 'init') {
                params.query = `roomId=${data.id}`
            } else {
                params.query = `roomId=${this.inputFrom.roomId}`
            }

            params.offset = (params.page - 1) * params.limit // 后端从0开始，0：第一页...
            EsAjax.post(ApiUrls.roomComposeList, { query: params.query, sort: params.sort, order: params.order, offset: params.offset, limit: 10 }).then(res => {
                if (res.data.code && res.data.code === 200) {
                    res.data.data.list.forEach((item) => {
                        if (item.exeConfig) {
                            item.exeConfig = JSON.parse(item.exeConfig)
                        }
                        if (item.output) {
                            item.output = JSON.parse(item.output)
                        }
                    })
                    this.linkTable = res.data.data.list
                    this.total1 = res.data.data.totalCount

                    if (this.isOpenRowStr !== '') {
                        // 改变【执行】/【状态输出】选择实时更新执行内容
                        this.linkTable.forEach((item) => {
                            if (this.isOpenRowId === item.id) {
                                if (this.isOpenRowStr === 'exeConfig') {
                                    this.resExeConfig = item.exeConfig
                                } else if (this.isOpenRowStr === 'output') {
                                    this.resOutput = item.output
                                }
                                this.openRowContent(this.isOpenRowId, this.isOpenRowStr)
                            }
                        })
                    }
                    this.linkLoading = false
                    this.setCurLinkRow()
                }
            }).catch(err => {
                this.linkLoading = false
            })
            // console.log(params.offset);

        },
        handleAdd() {
            this.$refs.editDialogRef.show(null, '添加');
        },
        setSelectClassRows(val) {
            this.selectItems = []
            val.forEach((item) => {
                this.selectItems.push(item)
            })
        },
        // 切换 教室列表 行
        onRowClick(row, column) {
            this.isCurrentLinkRowId = ''
            this.multiple = []
            this.multiple.push(row)
            this.linkTable = []
            this.$refs.multipleTable.setCurrentRow(row)
            this.$refs.isLinkTable.setCurrentRow()
            setTimeout(() => {
                this.initLink({}, '')
            }, 500)
        },
        handleEdit(row) {
            this.$refs.editDialogRef.show(row.id, '编辑 ', row);
        },
        setIds(val) {
            let ids = ''
            if (val.length === 1) {
                ids = val[0].id.toString()
            } else {
                let arr = val.map((item) => {
                    return item.id
                })
                ids = arr.join(',')
            }
            return ids
        },
        // handleCreate() {
        //     if (!this.selectItems.length) {
        //         this.$message.warning('请先勾选要生成的教室配置')
        //         return false
        //     }
        //     let _ids = this.setIds(this.selectItems)
        //     EsAjax.post(ApiUrls.batchGenConfig, { ids: _ids }).then(res => {
        //         if (res.data.code && res.data.code === 200) {
        //             this.$message({
        //                 type: 'success',
        //                 message: res.data.msg,
        //             })
        //             this.initClassRoom()
        //         }
        //     })

        // },
        handleIssue() {
            if (!this.selectItems.length) {
                this.$message.warning('请先勾选要下发的教室配置')
                return false
            }
            let _ids = this.setIds(this.selectItems)
            EsAjax.post(ApiUrls.batchGenConfig, { ids: _ids }).then(res => {
                if (res.data.code && res.data.code === 200) {
                    EsAjax.post(ApiUrls.batchUpdateConfig, { ids: _ids }).then(res => {
                        if (res.data.code && res.data.code === 200) {
                            this.$message({
                                type: 'success',
                                message: res.data.msg,
                            })
                            this.initClassRoom()
                        }
                    })
                }
            })

        },
        handleChange(value) {
            console.log(value);
            this.iptNum = value
        },
        handleCopy() {
            // this.$message.warning('功能开发中...')
            if (!this.selectItems.length) {
                this.$message({
                    type: 'warning',
                    message: '请选择要复制的数据!',
                })
                return false
            }
            console.log(this.selectItems);

            this.selectItems.forEach((item) => {
                // let newObj = {
                //     id: 'id_' + Math.random().toString(36).slice(2),
                //     newClassIP: '',
                //     ip: item.ip,
                //     newName: '',
                //     name: item.name,
                //     editStatus: false,
                // }
                // this.classTable.push(newObj)
                let params = {
                    copyRoomId: item.id,
                    copyValue: this.iptNum
                }
                EsAjax.post(ApiUrls.batchCopy, params).then(res => {
                    console.log(res);
                    if (res.data.code === 200) {
                        this.initClassRoom()
                    }
                })
            })
            // this.$refs.multipleTable.clearSelection()
        },
        handleDelLeft() {
            if (!this.selectItems.length) {
                this.$message.warning('请先勾选要删除的教室配置')
                return false
            }
            let _ids = this.setIds(this.selectItems)
            console.log(_ids);
            EsAjax.post(ApiUrls.classRoomDel, { ids: _ids }).then(res => {
                console.log(res);
                if (res.data.code && res.data.code === 200) {
                    this.$message({
                        type: 'success',
                        message: res.data.msg,
                    })
                    this.initClassRoom()
                }
            })

        },
        handleNewLink() {
            let newObj = {
                id: 0,
                deviceIp: '',
                input: '',
                exeConfig: [],
                output: '',
            }
            this.linkTable.push(newObj)
        },

        setSelectLinkRows(val) {
            this.selectLinkItems = []
            val.forEach((item) => {
                this.selectLinkItems.push(item)
            })
        },
        handleDelRight() {
            if (!this.selectLinkItems.length) {
                this.$message.warning('请先勾选要删除的关联配置')
                return false
            }
            let _ids = this.setIds(this.selectLinkItems)
            EsAjax.post(ApiUrls.roomComposeDel, { ids: _ids }).then(res => {
                if (res.data.code && res.data.code === 200) {
                    this.$message({
                        type: 'success',
                        message: res.data.msg,
                    })
                    this.initLink({}, '')
                }
            })

        },
        // 获取设备列表
        getLinkDeviceList() {
            let params = {
                query: '',
                sort: 'Id',
                order: 'desc',
                offset: 0,
                limit: 100,
            }
            EsAjax.post(ApiUrls.equipmentTypeList, params).then(res => {
                if (res.data.code && res.data.code === 200) {
                    console.log(res);
                    if (this.dialogCommand) {
                        this.deviceListTable = res.data.data.list
                    } else if (this.dialogVisible) {
                        this.commonTable = res.data.data.list
                    }
                }
                this.commandLoading = false
                this.commonLoading = false
            })
        },
        // 切换 命令输入列表 行
        onRowClickDevice(row, column) {
            this.curRadio = ''
            this.inputFrom.deviceId = row.id
            this.inputFrom.deviceIp = row.ip ? row.ip : ''
            this.checkOpt = []
            this.checkOpt = row.actions !== '' ? JSON.parse(row.actions) : []
            this.$refs.deviceTable.setCurrentRow(row)
        },
        // 命令输入编辑
        rowCommand(row, inx) {
            console.log(row, inx);
            this.rowName = inx
            this.rowNameId = row.deviceId
            this.isCurrentLinkRowId = row.id
            this.inputFrom.id = row.id
            this.dialogCommand = true
            this.commandLoading = true
            this.curRadio = ''
            this.checkOpt = []
            this.getLinkDeviceList()
        },
        // 数据去重
        removal(arr, str) {
            let len = arr.length
            for (let i = 0; i < len; i++) {
                for (let j = i + 1; j < len; j++) {
                    if (
                        arr[i].id === arr[j].id &&
                        arr[i].action === arr[j].action &&
                        arr[i].communication === arr[j].communication &&
                        arr[i].outputValue === arr[j].outputValue
                    ) {
                        arr.splice(j, 1)
                        len-- // 减少循环次数提高性能
                        j-- // 保证j的值自加后不变
                    }
                }
            }
            if (str === 'output') {
                this.resOutput.forEach((el) => {
                    arr.forEach((item) => {
                        if (
                            el.deviceId === item.id &&
                            el.action === item.action &&
                            el.communication === item.communication &&
                            el.outputValue === item.outputValue
                        ) {
                            item.sort = el.sort
                        }
                    })
                })
            } else {
                this.resExeConfig.forEach((el) => {
                    arr.forEach((item) => {
                        if (
                            el.deviceId === item.id &&
                            el.action === item.action &&
                            el.communication === item.communication
                        ) {
                            item.sort = el.sort
                        }
                    })
                })
            }
            // 数组排序
            arr.sort((a, b) => {
                return a.sort - b.sort
            })
            return arr
        },
        dataEcho() {
            // 执行 行为/延时 数据回显
            this.carryOutTable.forEach((item) => {
                this.resExeConfig.forEach((el, inx) => {
                    if (
                        item.id === el.deviceId &&
                        item.action === el.action &&
                        item.communication === el.communication
                    ) {
                        item.checked = true
                        item.delay = el.delay
                    }
                })

                if (item.checked) {
                    // 执行内容数据回显
                    this.connectTable.push(item)
                    this.connectTable = this.removal(this.connectTable)
                }
            })
        },
        outputDataEcho() {
            // 输出 数据回显
            this.statusCheckOpt.forEach((item) => {
                this.resOutput.forEach((el, inx) => {
                    if (
                        item.id === el.deviceId &&
                        item.action === el.action &&
                        item.communication === el.communication
                    ) {
                        item.outputValue = el.outputValue
                    }
                })
                // 执行内容数据回显
                if (item.outputValue !== '') {
                    this.connectTable.push(item)
                    // this.connectTable = this.removal(this.connectTable, 'output')
                }
            })
        },
        // 执行/状态输出公共设备列表切换
        onRowClickCommonDevice(row, column) {
            if (this.flag) {
                // this.carryOutFrom.module = row.module
                this.carryOutTable = []
                let resArr = []
                if (row.actions !== '' && row.actions.length) {
                    resArr = JSON.parse(row.actions)
                    resArr.forEach((item) => {
                        item.checked = false
                        item.delay = ''
                        item.id = row.id
                        item.module = row.module
                    })
                }
                this.carryOutTable = row.actions !== '' ? resArr : []
                this.dataEcho()
            } else {
                // this.statusFrom.module = row.module
                let resArr2 = []
                if (row.action !== '' && row.actions.length) {
                    resArr2 = JSON.parse(row.actions)
                    resArr2.forEach((item) => {
                        item.id = row.id
                        item.module = row.module
                        item.outputValue = ''
                        item.list = [
                            {
                                code: 1,
                                label: '开',
                            },
                            {
                                code: 0,
                                label: '关',
                            },
                        ]
                    })
                }
                this.statusCheckOpt = []
                this.statusCheckOpt = row.actions !== '' ? resArr2 : []
                this.outputDataEcho()
            }
            this.$refs.commonDeviceTable.setCurrentRow(row)
        },
        // 打开【执行】/【状态输出】回显弹窗执行内容
        openRowContent(val, str) {
            this.linkTable.forEach((item) => {
                if (item.id === val) {
                    if (str === 'exeConfig') {
                        let exeArr = []
                        if (item.exeConfig.length) {
                            var arr = item.exeConfig
                            var len = arr.length
                            for (let i = len - 1; i >= 0; i--) {
                                arr[i].id = arr[i].deviceId
                                for (let j = i - 1; j >= 0; j--) {
                                    if (arr[i].sort === arr[j].sort) {
                                        if (arr[j].deviceId === -1 && arr[j].action) {
                                            arr[i].delay = arr[j].action
                                        }
                                        arr.splice(j, 1)
                                        len-- // 减少循环次数提高性能
                                        i-- // 减少循环次数提高性能
                                        j-- // 保证j的值自加后不变
                                    }
                                }
                                exeArr = arr
                            }
                        }
                        this.connectTable = exeArr
                        console.log(this.connectTable);
                    } else if (str === 'output') {
                        let outputArr = []
                        if (item.output.length) {
                            let arr = item.output
                            let len = arr.length
                            for (let i = 0; i < len; i++) {
                                arr[i].id = arr[i].deviceId
                                for (let j = i + 1; j < len; j++) {
                                    if (
                                        arr[i].deviceId === arr[j].deviceId &&
                                        arr[i].action === arr[j].action &&
                                        arr[i].communication === arr[j].communication &&
                                        arr[i].outputValue === arr[j].outputValue
                                    ) {
                                        arr[i].outputValue = arr[j].outputValue
                                        arr.splice(j, 1)
                                        len-- // 减少循环次数提高性能
                                        j-- // 保证j的值自加后不变
                                    }
                                }
                                outputArr = arr
                            }
                        }
                        this.connectTable = outputArr
                    }
                }
            })
            this.connectLoading = false

            this.connectTable.forEach((item) => {
                if (
                    this.curOutputRowId === item.id &&
                    this.curRow.action === item.action
                ) {
                    this.curRow = item
                    this.$refs.connectTable.setCurrentRow(item)
                }
            })
        },
        // 执行编辑
        rowCarryOut(row, str) {
            console.log(row, str);
            console.log(this.linkTable);
            this.shanchuflog = false
            this.isCurrentLinkRowId = row.id
            this.isOpenRowId = row.id
            this.isOpenRowStr = str
            this.resExeConfig = []
            this.connectTable = []
            if (!row.id) {
                this.$message.warning('请先编辑命令输入信息!')
                return false
            }
            if (row.exeConfig) {
                this.resExeConfig = row.exeConfig
            }
            this.carryOutFrom.id = row.id
            this.dialogTitle = '执行'
            this.flag = true
            this.carryOutLoading = false
            // this.carryOutTable = []
            this.dialogVisible = true
            this.commonLoading = true
            this.getLinkDeviceList()
            this.openRowContent(this.isOpenRowId, this.isOpenRowStr)
        },

        actionClick(row) {
            if (row.checked) {
                this.connectTable.push(row)
            }
            // 取消已选择行为
            if (!row.checked) {
                row.delay = ''
                this.connectTable.forEach((item, inx) => {
                    if (item.id === row.id && item.action === row.action) {
                        this.connectTable.splice(inx, 1)
                    }
                })
            }
            this.connectLoading = true
            this.addExeConfig()
        },
        delayInput(row) {
            if (!row.checked) {
                this.$message.warning('请先选择行为!')
                row.delay = ''
                return false
            }
            this.connectTable.forEach((item) => {
                if (item.id === row.id && item.action === row.action) {
                    item.delay = row.delay
                }
            })
            this.connectLoading = true
            this.addExeConfig()
        },
        // //联动IP输入
        // IPInput(row) {
        //     this.$message.warning('联动IP')
        // },
        // 状态输出编辑
        rowStatus(row, str) {
            // console.log(row,str);
            this.shanchuflog = true
            this.isCurrentLinkRowId = row.id
            this.isOpenRowId = row.id
            this.isOpenRowStr = str
            this.resOutput = []
            this.connectTable = []
            if (!row.id) {
                this.$message.warning('请先编辑命令输入信息!')
                return false
            }
            if (row.output) {
                this.resOutput = row.output
            }
            this.statusFrom.id = row.id
            this.dialogTitle = '状态输出'
            this.flag = false
            this.statusTitle = '按钮状态'
            this.dialogVisible = true
            this.commonLoading = true
            this.getLinkDeviceList()
            this.openRowContent(this.isOpenRowId, this.isOpenRowStr)
        },

        handleStatusRadio(val) {
            // console.log(val);
            this.testarr.push(JSON.parse(JSON.stringify(val)))
            console.log(this.testarr);

            if (val.outputValue !== '') {
                this.connectTable.push(...this.testarr)
                this.testarr = []
                // this.connectTable.push(val)
            }
            // return
            // this.connectTable.forEach((item) => {
            //   if (
            //     item.id === val.id &&
            //     item.action === val.action &&
            //     item.communication === val.communication
            //   ) {
            //     item.outputValue = val.outputValue
            //   }
            // })
            // console.log(this.connectTable);
            this.connectLoading = true
            this.addOutput()
        },
        // 保存命令输入
        addBehavior() {
            let params = this.inputFrom
            EsAjax.post(ApiUrls.editInput, params).then(res => {
                this.initLink({}, '')
            })

        },
        // 切换 命令输入 行为
        curItemRadio(val) {
            this.checkOpt.forEach((item) => {
                let resStr = item.communication + item.action
                if (resStr === val) {
                    this.inputFrom.communication = item.communication
                    this.inputFrom.action = item.action
                }
            })
        },
        // 命令输入 确认
        confirmDialog() {
            if (!this.curRadio) {
                this.$message.warning('请选择行为')
                return false
            }
            this.addBehavior()
            this.curRadio = ''
            this.dialogCommand = false
        },
        // 命令输入 取消
        cancelDialog() {
            this.dialogCommand = false
        },
        // 排序用-选择要排序的行
        onRowClickSort(row) {
            this.curRow = row
            this.curOutputRowId = row.id
            this.$refs.connectTable.setCurrentRow(row)
            if (!this.commonTable.length) return false
            this.commonTable.forEach((item) => {
                if (item.id === row.id) {
                    if (this.flag) {
                        // this.carryOutFrom.module = row.module
                        this.carryOutTable = []
                        let resArr = []
                        if (item.actions !== '') {
                            resArr = JSON.parse(item.actions)
                            resArr.forEach((ele) => {
                                ele.checked = false
                                ele.delay = ''
                                ele.id = item.id
                                ele.module = item.module
                                if (
                                    ele.id === row.id &&
                                    ele.action === row.action &&
                                    ele.communication === row.communication
                                ) {
                                    ele.checked = true
                                    ele.delay = row.delay
                                }
                            })
                        }
                        this.carryOutTable = item.actions !== '' ? resArr : []
                    } else {
                        // this.statusFrom.module = row.module
                        let resArr2 = []
                        if (item.action !== '') {
                            resArr2 = JSON.parse(item.actions)
                            resArr2.forEach((ele) => {
                                ele.id = item.id
                                ele.module = item.module
                                ele.outputValue = ''
                                ele.list = [
                                    {
                                        code: 1,
                                        label: '开',
                                    },
                                    {
                                        code: 0,
                                        label: '关',
                                    },
                                ]
                                if (
                                    ele.id === row.id &&
                                    ele.action === row.action &&
                                    ele.communication === row.communication
                                ) {
                                    ele.outputValue = row.outputValue
                                }
                            })
                        }
                        this.statusCheckOpt = []
                        this.statusCheckOpt = item.actions !== '' ? resArr2 : []
                    }
                    this.$refs.commonDeviceTable.setCurrentRow(item)
                }
            })
        },
        swapArray(arr, index1, index2) {
            arr[index1] = arr.splice(index2, 1, arr[index1])[0]
            return arr
        },
        // 上移
        arrowUP() {
            let index = this.curRow.order - 1
            if (index === 0) {
                this.$message.warning('已经是第一行了!')
            } else {
                this.swapArray(this.connectTable, index - 1, index)
                if (this.flag) {
                    this.addExeConfig()
                } else {
                    this.addOutput()
                }
            }
        },
        // 下移
        arrowDown() {
            let index = this.curRow.order - 1
            if (index === this.connectTable.length - 1) {
                this.$message.warning('已经是最后一行了!')
            } else {
                this.swapArray(this.connectTable, index, index + 1)
                if (this.flag) {
                    this.addExeConfig()
                } else {
                    this.addOutput()
                }
            }
        },
        // 新增/编辑 执行
        addExeConfig() {
            let exeConfig = []
            if (this.connectTable.length) {
                this.connectTable.forEach((item, inx) => {
                    let obj = {}
                    let delayObj = {}
                    if (item.delay !== '') {
                        delayObj.sort = inx + 1
                        delayObj.deviceId = -1
                        delayObj.id = item.id
                        delayObj.module = item.module
                        delayObj.action = item.delay
                        obj.communication = item.communication
                        exeConfig.push(delayObj)
                    }
                    obj.sort = inx + 1
                    obj.deviceId = item.id
                    obj.module = item.module
                    obj.action = item.action
                    obj.communication = item.communication
                    exeConfig.push(obj)
                })
            }
            let params = {
                id: this.carryOutFrom.id,
                roomId: this.carryOutFrom.roomId,
                config: JSON.stringify(exeConfig),
            }
            EsAjax.post(ApiUrls.editExe, params).then(res => {
                this.connectLoading = false
                if (res.data.code && res.data.code === 200) {
                    this.initLink({}, '')
                }
            })

        },

        // 新增/编辑 输出
        addOutput() {
            let output = []
            console.log(this.connectTable);
            if (this.connectTable.length) {
                this.connectTable.forEach((item, inx) => {
                    let obj = {}
                    obj.sort = inx + 1
                    obj.deviceId = item.id
                    obj.action = item.action
                    obj.module = item.module
                    obj.communication = item.communication
                    obj.outputValue = item.outputValue
                    output.push(obj)
                })
            }
            let params = {
                id: this.statusFrom.id,
                roomId: this.statusFrom.roomId,
                config: JSON.stringify(output),
            }
            EsAjax.post(ApiUrls.editOutput, params).then(res => {
                this.initLink({}, '')
            })
        },
        // 执行/状态输出 确认
        commonConfirm() {
            // this.addOutput()
            this.commonCancel()
        },
        // 执行/状态输出 取消
        commonCancel() {
            this.curOutputRowId = '' //输出内容id排序,关闭弹窗置空
            this.isOpenRowId = ''
            this.isOpenRowStr = ''
            this.resExeConfig = []
            this.resOutput = []
            this.dialogTitle = ''
            this.commonTable = []
            if (this.flag) {
                this.carryOutTable = []
            } else {
                this.statusTitle = ''
                this.statusCheckOpt = []
            }
            this.flag = true
            this.connectTable = []
            this.dialogVisible = false
            this.initLink({}, '')
        },
        dialogVisibleClose() {
            this.commonCancel()
        },
        shanchu(row) {
            // console.log(row);
            this.connectTable.splice(row.sort - 1, 1)
            this.addOutput()
        }
    },

}
</script>
<style lang="scss" scoped>
::v-deep .el-table {
    --el-table-border-color: #191e4b
}

::v-deep .el-table th {
    background-color: #191e4b;

    .cell {
        font-weight: bold;
        color: #3c3c3c;
    }
}

::v-deep .el-dialog {
    padding: 20px 20px 40px;
}

::v-deep .el-dialog__header {
    padding: 0px 0px 10px 0px;

    .el-dialog__title {
        font-size: 16px;
        color: #2c3e50;
    }
}

::v-deep .el-dialog__body {
    border: none;
    padding: 0px;
    padding-bottom: 12px;
}

::v-deep .el-dialog__footer {
    text-align: center;
    padding: 26px 0px 0px;
}

.container {
    .content {
        display: flex;
        padding: 0px 16px;
    }

    .left-wrap {
        width: 40%;
    }

    .right-wrap {
        width: calc(60% - 50px);
        padding-left: 50px;
    }

    .btn-cont {
        display: flex;
    }

    .left {
        padding: 24px 0px;
        justify-content: space-between;
        align-items: center;
    }

    .bottom-l {
        padding: 40px 0px 16px 0px;
    }

    .right {
        padding: 24px 0px;
        justify-content: flex-end;
    }

    .bottom-r {
        justify-content: flex-end;
        padding: 40px 0px 16px 0px;
    }

    .table-cont {
        .input-cont {
            ::v-deep .el-input__inner {
                text-align: center;
            }
        }
    }
}

.row-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;

    ::v-deep .el-checkbox {
        margin-right: 6px;
    }

    ::v-deep .el-input {
        width: 100px;
        margin-right: 6px;
    }

    .row-cell {
        display: flex;
        align-items: center;
        width: 276px;
        overflow: hidden;

        .v_set {
            display: inline-block;
            font-weight: bold;
            padding: 0px 3px;
        }
    }
}

.behavior-row,
.delay-row {
    justify-content: flex-start;
}

::v-deep .current-row {
    td.el-table__cell {
        background-color: #409eff !important;

        div,
        span {
            color: #191e4b;
        }
    }
}

.dialog-cont {
    display: flex;

    .left-table {
        width: calc(100% - 200px);
        padding-right: 16px;
        box-sizing: border-box;
        border-right: 1px solid #dcdfe6;
    }

    .common-cont {
        width: calc(100% - 340px - 500px);
    }

    .list-cont {
        width: 300px;
        padding: 0px 16px;
        box-sizing: border-box;
        border-right: 1px solid #dcdfe6;
        // display: flex;
        flex-direction: column;
        align-items: center;

        .title {
            height: 40px;
            line-height: 40px;
            font-size: 14px;
            font-weight: bold;
            color: #3c3c3c;
            text-align: center;
        }

        .list {
            width: 100%;
            height: 160px;
            overflow-y: scroll;

            .item {
                height: 46px;
                line-height: 46px;
            }
        }
    }

    .list-center-cont {
        width: 340px;
        height: 530px;
        padding: 0px 16px;
        box-sizing: border-box;
        border-right: 1px solid #dcdfe6;
        display: flex;
        flex-direction: column;
        align-items: center;
        overflow-y: scroll;

        .title-status {
            height: 40px;
            line-height: 40px;
            font-size: 14px;
            font-weight: bold;
            color: #3c3c3c;
            text-align: center;
        }

        .list-status {
            width: 100%;
            height: 560px;
            overflow: scroll;

            .item-status {
                height: 46px;
                line-height: 46px;
                display: flex;
                align-items: center;
                justify-content: space-between;
            }

            .title-cont {
                min-width: 120px;
            }

            .el-radio-group {
                display: flex;
                align-items: center;
            }

            .ele-status {
                display: flex;
                align-items: center;
            }

            .ele-status:not(:first-child) {
                margin-left: 16px;
            }
        }
    }

    .right-table {
        width: 500px;
        padding: 0px 16px;
        box-sizing: border-box;
        border-right: 1px solid #dcdfe6;

        .btn-move-cont {
            display: flex;
            justify-content: center;
        }
    }
}

:deep(.el-radio-group) {
    display: block;
}
</style>
